package pit.com.ordermobilesystem.fragment;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pit.com.ordermobilesystem.BaseFragment;
import pit.com.ordermobilesystem.InvoiceActivity;
import pit.com.ordermobilesystem.R;
import pit.com.ordermobilesystem.ShopActivity;
import pit.com.ordermobilesystem.adapter.ImageFancyCoverFlowAdapter;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.provider.BaseProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider.ItemTable;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import at.technikum.mti.fancycoverflow.FancyCoverFlow;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ItemDetailFragment extends BaseFragment{
	int idItem;
	JSONObject item;
	View rootView;
	DisplayImageOptions options;	
	public ImageLoader imageLoader = ImageLoader.getInstance();
	FancyCoverFlow fancyCoverFlow;
	public ItemDetailFragment() {
		super();
		name="ItemDetailFragment";
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.ic_no_image)
		.showImageForEmptyUri(R.drawable.ic_no_image)
		.showImageOnFail(R.drawable.ic_no_image)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();			
	}



	@Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	            rootView = inflater.inflate(R.layout.fragment_detail_item, container, false);
		Bundle bundle =getArguments();
		idItem=bundle.getInt("item_id");
		String item_name=bundle.getString("item_name");
		getActivity().getActionBar().setTitle(getArguments().getString("item_name"));
		fancyCoverFlow=(FancyCoverFlow) rootView.findViewById(R.id.fancyCoverFlow);
		String link;
			try {
				Cursor data = getActivity().getContentResolver().query(
						OrderMobileProvider.ITEM_CONTENT_URI,null,  ItemTable.ID_ITEM+"="+idItem, null,
						null);
				if (data != null) {
					if(data.moveToNext()){
						try {
							item=BaseProvider.getJsonObjectFromCursor( data);
							JSONArray array;
							if(item.getString("list_image").equals("")){
								array=new JSONArray();
								array.put(item.getString(ItemTable.LINK_IMAGE));
							}else{
								array=new JSONArray(item.getString("list_image"));
							}
							
					        this.fancyCoverFlow.setAdapter(new ImageFancyCoverFlowAdapter(getActivity(),array,300,300));
					        this.fancyCoverFlow.setUnselectedAlpha(1.0f);
					        this.fancyCoverFlow.setUnselectedSaturation(0.0f);
					        this.fancyCoverFlow.setUnselectedScale(0.5f);
					        this.fancyCoverFlow.setSpacing(50);
					        this.fancyCoverFlow.setMaxRotation(0);
					        this.fancyCoverFlow.setScaleDownGravity(0.2f);
					        this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);						
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					data.close();
				}
				
				link = item.getString(ItemTable.LINK_IMAGE);
				TextView tv_title=(TextView) rootView.findViewById(R.id.tv_title);
				tv_title.setText(item.getString(ItemTable.NAME_ITEM));
				TextView tv_des=(TextView) rootView.findViewById(R.id.tv_description);
				tv_des.setText(item.getString(ItemTable.DESCRIPTION));
				TextView tv_price=(TextView) rootView.findViewById(R.id.tv_price);
				tv_price.setText(item.getString(ItemTable.PRICE));
				TextView tv_numberorder=(TextView) rootView.findViewById(R.id.tv_quantity);
				tv_numberorder.setText(item.getString(ItemTable.NUMBER_ORDER));
				TextView tv_sub=(TextView) rootView.findViewById(R.id.tv_sub);
				TextView tv_add=(TextView) rootView.findViewById(R.id.tv_add);
				tv_add.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						ContentValues updateAddValue=new ContentValues();
						
						try {
							updateAddValue.put(ItemTable.NUMBER_ORDER, item.getInt(ItemTable.NUMBER_ORDER)+1);
							getActivity().getContentResolver().update(OrderMobileProvider.ITEM_CONTENT_URI, updateAddValue, ItemTable.ID_ITEM+"="+idItem,null);
							getActivity().getContentResolver().notifyChange(OrderMobileProvider.ITEM_CONTENT_URI, null);						
							calculateTotalPrice();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			
						
					}
				});
				tv_sub.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
					ContentValues updateAddValue=new ContentValues();
						
						try {
							if(item.getInt(ItemTable.NUMBER_ORDER)>0){
								updateAddValue.put(ItemTable.NUMBER_ORDER, item.getInt(ItemTable.NUMBER_ORDER)-1);
								getActivity().getContentResolver().update(OrderMobileProvider.ITEM_CONTENT_URI, updateAddValue, ItemTable.ID_ITEM+"="+idItem,null);
								getActivity().getContentResolver().notifyChange(OrderMobileProvider.ITEM_CONTENT_URI, null);	
								calculateTotalPrice();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				calculateTotalPrice();
				TextView tv_payment=(TextView) rootView.findViewById(R.id.tv_payment);
				tv_payment.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						ShopActivity shopActivity=(ShopActivity) getActivity();
						shopActivity.onBackPressed();
						TextView tv_total_invoice=(TextView) rootView.findViewById(R.id.tv_total_invoice);
						Intent intent=new Intent(getActivity(),InvoiceActivity.class);
						intent.putExtra("total", tv_total_invoice.getText());
						startActivity(intent);
						
					}
				});
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return rootView;
	    }
	
	public void calculateTotalPrice(){
		
		try {			
			Cursor data = getActivity().getContentResolver().query(
					OrderMobileProvider.ITEM_CONTENT_URI,null,  ItemTable.ID_ITEM+"="+idItem, null,
					null);
			if (data != null) {
				if(data.moveToNext()){
					try {
						item=BaseProvider.getJsonObjectFromCursor( data);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				data.close();
			}	
			TextView tv_numberorder=(TextView) rootView.findViewById(R.id.tv_quantity);
			tv_numberorder.setText(item.getString(ItemTable.NUMBER_ORDER));			
			TextView tv_total_price=(TextView) rootView.findViewById(R.id.tv_total_price);
			JSONObject shop = new JSONObject(OrderSharePreference.getShop(getActivity()));
			tv_total_price.setText(""+item.getInt(ItemTable.NUMBER_ORDER)*Double.parseDouble(item.getString(ItemTable.PRICE)));
			String nameColumn="SUM("+ItemTable.PRICE+"*"+ItemTable.NUMBER_ORDER+") AS TOTAL";
			String[] column={nameColumn};
			 data = getActivity().getContentResolver().query(OrderMobileProvider.ITEM_CONTENT_URI, column,  ItemTable.NUMBER_ORDER+">0 AND "+ItemTable.SALE_ID+"="+shop.getInt("id"), null,null);
			if (data != null) {
				if(data.moveToNext()){
					TextView tv_total_invoice=(TextView) rootView.findViewById(R.id.tv_total_invoice);
					tv_total_invoice.setText(data.getString(data.getColumnIndex("TOTAL")));
				}
				data.close();
			}			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	

	class SubmitOrder extends AsyncTask<String, Void, Void> {

		TypeLoadingMore typeLoading;
		Exception exception;
		int response_code;
		
		
		public SubmitOrder(TypeLoadingMore typeLoading) {
			super();
			this.typeLoading = typeLoading;
		}
		protected void onPreExecute() {
			if(typeLoading==TypeLoadingMore.LOADING_FIRST){
				showProgressDialog(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						SubmitOrder.this.cancel(true);
						dialog.dismiss();
					}


				});
			}

		}

		protected Void doInBackground(final String... args) {
			OrderSystemHttpService httpService=new OrderSystemHttpService(OrderSharePreference.getHost(getActivity()),OrderSharePreference.getPort(getActivity()));
			try {
				JSONObject result=httpService.requestToService(OrderSystemHttpService.URL_GET_LIST_CATEGORY, "");
				if(result.getString("status").equals("ok")){		
					JSONArray arrayCategory=result.getJSONObject("data").getJSONArray("categories");
					ContentValues[] listValues=new ContentValues[arrayCategory.length()];					
					for(int i=0;i<arrayCategory.length();i++){
						listValues[i]=OrderMobileProvider.getContentValues(getActivity(),arrayCategory.getJSONObject(i));
					}
					//Insert into database
					getActivity().getContentResolver().bulkInsert(OrderMobileProvider.CATEGORY_CONTENT_URI, listValues);				
				}else{
					exception=new Exception(result.getString("error"));
				}

			} catch (UnsupportedEncodingException e) {
				exception=e;
			} catch (HttpApiException e) {
				exception=e;
			} catch (Exception e) {
				exception=e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {

				hideProgressDialog();

			
			if(exception!=null){
				showAlert("",exception.getMessage());
			}
			getActivity().getContentResolver().notifyChange(OrderMobileProvider.CATEGORY_CONTENT_URI, null);
		}

	}	

	
}
